package hn.security.configuration;

import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Pattern;

public class CsrfRequestMatcherImpl implements RequestMatcher {

    // 允许的请求方法（匹配模式）
    private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
    //需要排除的url列表
    private List<String> execludeUrls;

    public List<String> getExecludeUrls() {
        return execludeUrls;
    }

    public void setExecludeUrls(List<String> execludeUrls) {
        this.execludeUrls = execludeUrls;
    }


    @Override
    public boolean matches(HttpServletRequest httpServletRequest) {
        if (execludeUrls != null && execludeUrls.size() > 0) {
            String servletPath = httpServletRequest.getServletPath();
            for (String url : execludeUrls) {
                if (servletPath.contains(url)) {
                    return false;
                }
            }
        }
        return !allowedMethods.matcher(httpServletRequest.getMethod()).matches();
    }
}
